<?php
/**
 * Controller.php 入口控制器
 *
 * 系统入口控制器,所有模块控制器继承此类
 *
 * @author          hyperblue
 * @version         0.1
 * @copyright       (C) 2011- *
 * @license	        http://www.bingceng.com
 * @lastmodify	    2011-11-17 16:10
 */
 
defined('BC_INC_PATH') or exit("Access Denied!");

require_once BC_CORE_PATH.'Model.php';

class Controller {

	static private $_instance; //对象句柄
	
    static private $route_config = array(); //路由默认配置
    
	/**
	 * 构造函数
	 *
	 */
    public function __construct() {
		self::route();
		
		$this->tpl = new tpl;
		$this->lang = new lang;
    }
	
	/**
	 * 创建应用程序
	 *
	 */
	public function GO() {
   		self::timer('start');
		global $_config, $admin_rights;
		
		//if (ROUTE_M == $_config['admin_module'] && is_array($admin_rights[1][ROUTE_C]) && !in_array(ROUTE_A, $admin_rights[1][ROUTE_C])) die('无权访问！');
		if (ROUTE_M == $_config['admin_module'] && ROUTE_A != 'login') {
			if (!$_SESSION['bc_backend']['user_id']) {
				_redirect(_url($_config['admin_module'].'/index/login/', array('error' => 'error_login_unlogin')));
				exit();
			}
		}
		
		$controller_file = BC_CORE_PATH.ROUTE_M.DS.'controllers'.DS.ROUTE_C.'.php';

		if (file_exists($controller_file)) {
		    $classname = ROUTE_C;
			include $controller_file;
			$controller = new $classname;
			if (method_exists($controller, 'do_'.ROUTE_A)) {
				ob_start();
				//$controller->{'do_'.ROUTE_A}();
			    call_user_func(array($controller, 'do_'.ROUTE_A));
				$output = ob_get_contents();
      			ob_end_clean();
				self::timer('end');
     			echo str_replace('{RUN_TIME}',sprintf('%0.5f',self::timer('start','end')),$output);
		    } else {
			    exit('Action does not exist.');
		    }
		} else {
			exit('Controller does not exist.');
		}
		
	}
	
	/**
	 * 装载模型
	 *
	 */
	public function load_model($modelname = '', $module = '', $instantiated = true) {
	    $modelname = $modelname ? $modelname : strtolower(ROUTE_M);
	    $module = $module ? strtolower($module) : ROUTE_M;
	    
	    $model_file = BC_CORE_PATH.$module.DS.'models'.DS.$modelname.'.php';
	    
	    if (file_exists($model_file)) {
	        include $model_file;
	        if ($instantiated) {
	            $model = new $modelname;
	            return $model;
	        }
	    }

	}

	/**
	 * 路由，初始化模块,控制器,动作以及其他参数
	 *
	 */
	public function route() {
		global $_route_config;
		$base_params = array('m', 'c', 'a');
		$pathinfo = array();
		
		self::$route_config = $_route_config;
		
		if (BC_REWRITE) { //伪静态模式
			if (isset($_SERVER['PATH_INFO'])) $pathinfo = explode('/', trim($_SERVER['PATH_INFO'], '/'));
			$_GET['m'] = $pathinfo[0];
			$_GET['c'] = $pathinfo[1];
			$_GET['a'] = $pathinfo[2];
			$params = F_array_value2key(array_slice($pathinfo, 3));
			foreach($params as $key => $value) {
				$_GET[$key] = $value;
			}
        } else { //普通参数模式
		}
		foreach ($base_params as $key => $param) {
			$_GET[$param] = isset($_GET[$param]) && !empty($_GET[$param]) ? $_GET[$param] : (isset($_POST[$param]) && !empty($_POST[$param]) ? $_POST[$param] : '');
			$_GET[$param] = $_GET[$param] ? $_GET[$param] : self::$route_config[$param];
		}
		
		$_GET['m'] = strtolower($_GET['m']);
		
		define('ROUTE_M', $_GET['m']);
		define('ROUTE_C', $_GET['c']);
		define('ROUTE_A', $_GET['a']);
		
		//全局过滤
		global_filter();
	}
	
   /**
    * 运行时间
    *
    * 获取设置时间值
    *
    * @access  public
    * @param   string $id the timer id to set (or compare with $id2)
    * @param   string $id2 the timer id to compare with $id
    * @return  float  difference of two times
    */    
    public static function timer($id=null,$id2=null) {
    	static $times = array();
    	if($id !== null && $id2 !== null)
      		return (isset($times[$id]) && isset($times[$id2])) ? ($times[$id2] - $times[$id]) : false;
    	elseif($id !== null)
      		return $times[$id] = microtime(true);
    	return false;
  	}
    
	/**
	 * 获取实例
	 *
	 */
	static public function get_instance() {
		if (!self::$_instance) {
			self::$_instance = new Controller;
		}
		
		return self::$_instance;
	} 
    
	/**
	 * 克隆魔术方法
	 *
	 */
    private function __clone() {}
}
?>
